package StudyCode.Component;

import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

/**
 * @author lixiaoyao
 * @date 2018/11/22 0022、下午 1:10
 * @description 预览图片控件
 */
public class ImagePreViewer extends JLabel {

	public ImagePreViewer(JFileChooser fileChooser) {
		setPreferredSize(new Dimension(100, 100));
		setBorder(BorderFactory.createEtchedBorder());

		fileChooser.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent evt) {
				if (evt.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
					// the user has selected a new file
					File file = (File) evt.getNewValue();
					if (file == null) {
						setIcon(null);
						return;
					}

					// read the image into an icon
					ImageIcon imageIcon = new ImageIcon(file.getPath());

					// if the icon is too large to fit,scale it
					if (imageIcon.getIconWidth() > getWidth()) {
						imageIcon = new ImageIcon(imageIcon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
						setIcon(imageIcon);
					}
				}
			}
		});
	}

}
